import fs from 'fs'
import path from 'path'

/**
 * 第一层目录为nav，第二层为menu
 */

const docsPath = path.dirname(path.join(__dirname)); // docs 目录路径

const navConfig = []
const sidebarConfig = [generateSidebarConfig(docsPath)];
function generateSidebarConfig(docsPath, link = '', index = 0) {
    const sidebarConfig = {};

    //获取目录文件
    const files = fs.readdirSync(docsPath);

    files.forEach((filename) => {
        if (filename.startsWith(".")||filename==='node_modules') return;
        const filepath = path.join(docsPath, filename);
        const stat = fs.statSync(filepath);
        // 如果是文件夹，则递归生成子级 sidebar 配置
        console.log(filepath,`${link}${filename}`,stat.isDirectory())
        if (stat.isDirectory()) {
            if (index === 0) {
                navConfig.push({ text: `${filename}`, link: `/${filename}` })
                // const config = generateSidebarConfig(filepath, `/${filename}/`, index + 1);
                // if (!sidebarConfig[`/${filename}/`]) {
                //     sidebarConfig[`/${filename}/`] = [config];
                // }
            }
            if (!sidebarConfig.items) {
                sidebarConfig.items = [];
            }
            sidebarConfig.text=filename
            console.log(sidebarConfig)
            sidebarConfig.items.push(generateSidebarConfig(filepath, `${link}${filename}/`, index + 1))

        } else {
            // const extname = path.extname(filepath);
            // const basename = path.basename(filepath, extname);
            // const menuPath = path.dirname(filepath);
            // const menuName = path.basename(menuPath)
            // if (extname === ".md"){
            //     sidebarConfig.text = menuName;
            //     sidebarConfig.link = `${link}${basename}`;
            //
            // }
           /* if (filename === 'index.md' && index > 0) {
                const menuPath = path.dirname(filepath);
                const menuName = path.basename(menuPath)
                sidebarConfig.text = menuName;
                sidebarConfig.link = link;
            }
            if (extname === ".md" && filename !== "index.md") {
                if (!sidebarConfig.items) {
                    sidebarConfig.items = [];
                }
                sidebarConfig.items.push({
                    text: basename,
                    link: `${link}${basename}`,
                });
            }*/
        }
    });

    return sidebarConfig;
}
export  default {sidebarConfig,navConfig};